package com.ocom.common.entity.typehandler;

import com.ocom.common.utils.AES;
import com.ocom.common.utils.CommonUtil;
import com.ocom.common.utils.DESUtils;
import com.ocom.common.utils.MD5;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @Description: TODO
 * @Author: 朱晖
 * @Date: 2022/8/12
 **/
public class PersonPhoneHandle extends BaseTypeHandler<String> {

	String secret = "45os6zphhu4bp5bzrifhh01pvepif3bs";

	@Override
	public void setNonNullParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType) throws SQLException {
		ps.setString(i, encrypt(parameter, 1l));
	}

	@Override
	public String getNullableResult(ResultSet rs, String columnName) throws SQLException {
		String columnValue = rs.getString(columnName);
		return decrypt(columnValue, 1l);
	}

	@Override
	public String getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
		String columnValue = rs.getString(columnIndex);
		return decrypt(columnValue, 1l);
	}

	@Override
	public String getNullableResult(CallableStatement cs, int columnIndex)
			throws SQLException {
		String columnValue = cs.getString(columnIndex);
		return decrypt(columnValue, 1l);
	}

	public String encrypt(String parameter, Long companyId) {
		if (CommonUtil.isNull(parameter)) {
			return parameter;
		}
		String value = "";
		try {
			value = DESUtils.encrypt(parameter, secret);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return value;
	}

	public String decrypt(String parameter, Long companyId) {
		if (CommonUtil.isNull(parameter)) {
			return parameter;
		}
		String value = "";
		try {
			value = DESUtils.decrypt(parameter, secret);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return value;
	}

	public static String staticEncrypt(String parameter, Long companyId) {
		String key = MD5.MD5Encode(companyId.toString(), "utf8");
		return AES.encrypt(parameter, key);
	}

	public static String staticDecrypt(String parameter, Long companyId) {
		String key = MD5.MD5Encode(companyId.toString(), "utf8");
		return AES.decrypt(parameter, key);
	}
}

